﻿/*
 * Programer: JR Padfield
 * Description:
 * Version: 1
 * Date: 12/17/13 * 
 */

using Lidgren.Network;
using TheWorld.Components;

namespace TheWorld.Networking
{
    class Network
    {
        // private constructor
        private Network() { }

        // singleton accessor
        static Network _instance;
        public static Network Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new Network();
                return _instance;
            }
        }

        // TCP CLient
        public NetClient TcpClient;

        // init netowrk controller
        public void InitNetwork()
        {
            var config = new NetPeerConfiguration("Crzy Mirage");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.ConnectionTimeout = 5;
            TcpClient = new NetClient(config);
            TcpClient.Start();

            // Check if server is online //
            TcpClient.DiscoverKnownPeer("127.0.0.1", 6265);
            //Connect("127.0.0.1", 6265);
        }

        private void Connect(string host, int port)
        {
            TcpClient.Start();
            NetOutgoingMessage hail = TcpClient.CreateMessage("This is the hail message");
            TcpClient.Connect(host, port, hail);
        }

        public void ShutDown()
        {
            TcpClient.Disconnect("Requested by user");
        }

        public void SendData(NetOutgoingMessage data)
        {
            TcpClient.SendMessage(data, NetDeliveryMethod.ReliableOrdered);
        }

        // Check incoming mesages
        public void RecieveData()
        {
            NetIncomingMessage im;
            while ((im = TcpClient.ReadMessage()) != null)
            {
                // handle incoming messaage
                switch (im.MessageType)
                {
                    case NetIncomingMessageType.DiscoveryResponse:
                        TcpClient.Connect(im.SenderEndPoint); break;     
                    case NetIncomingMessageType.Data:
                        HandleTCP.Instance.HandleData(im);
                        break;
                    case NetIncomingMessageType.StatusChanged:
                        if ((NetConnectionStatus)TcpClient.ConnectionStatus == NetConnectionStatus.Disconnected)
                        {
                            // Leave the game and go back to main menu.
                            Client.StateManager.ChangeState(Client.MainMenuScreen);
                            // Clear list of other players.
                            Mapping.Instance.Worlds.Levels[Mapping.Instance.Worlds.CurrentLevel].Characters.Clear();
                        }
                        break;
                    default:
                        break;
                }

            }
        }
    }
}
